import { Context } from 'koishi'
import { UUID } from "uuidjs"
import { defaultUserInfo } from "./defaultData";
import { UserInfo, Plant } from "./type";
import dayjs from "dayjs"
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration) // 挂载duration插件



// 记录错误
const recordError = async (ctx: Context, messageData: any, err: any) => {
    ctx.database.create('errorTotal', {
        id: UUID.generate(),
        error: err,
        messageData: messageData,
        time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    })
}

// 获取阳光收集达到上限的时间
// 传入参数：当前阳光数量，最大阳光数量，下次收获时间，阳光生产时间，阳光生产量
const getSunLimitTime = (sun: number, maxSun: number, sunNextDropTime: string, sunDropTime: number, sunDropCount: number) => {
    if ((maxSun - sun) <= 0) return 0
    // 距离下次收获需要的时间
    let nextTime = dayjs(sunNextDropTime).diff(dayjs(), 'second')
    // 避免负数
    if (nextTime < 0) nextTime = 0
    if ((maxSun - sun - sunDropCount) <= 0) return nextTime
    else {
        // 距离阳光达到上限
        const limit = maxSun - sun - sunDropCount
        // 需要的时间
        const time = Math.ceil(limit / sunDropCount) * sunDropTime
        return nextTime + time
    }
}

// 格式化时间 秒数转时分秒
const formatTimeSecondToHMS = (second: number) => {
    if (second <= 0) return '00:00:00'
    const dur = dayjs.duration(second, 'seconds');
    const hours = String(dur.hours()).padStart(2, '0');
    const minutes = String(dur.minutes()).padStart(2, '0');
    const secs = String(dur.seconds()).padStart(2, '0');
    return `${hours}:${minutes}:${secs}`;
}

const render = async(ctx: Context, content: string, isLongText: boolean = false) => {
    let res = await ctx.puppeteer.render(
        `<html>
            <head>
                <style>
                    @font-face {
                    font-family: AlibabaPuHuiTi-2-55-Regular;
                    src:url(https://puhuiti.oss-cn-hangzhou.aliyuncs.com/AlibabaPuHuiTi-2/AlibabaPuHuiTi-2-55-Regular/AlibabaPuHuiTi-2-55-Regular.woff2) format('woff2');
                    }
                    html {
                    font-family: 'AlibabaPuHuiTi-2-55-Regular', 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
                    width: max-content;
                    height: 0;
                    background: white;
                    max-width: 600px;
                    min-width: 200px;
                    background-image: url(https://pic.imgdb.cn/item/66656e745e6d1bfa05aee62b.jpg);
                    background-size: 120px 120px;
                    ${isLongText && 'transform: scale(0.6);'}
                    }
                    p {
                    padding: 10px;
                    word-wrap: break-word;
                    white-space: pre-wrap;
                    font-size: 12px;
                    color: #eee;
                    }
                </style>
                </head>
                <body>
                <p>${content}</p>
                </body>
            </html>`);
    return res
}

// 种植与铲除植物连携 -  重新计算阳光生产信息
const recalculateSunInfo = (userInfo: UserInfo, plantList: Array<Plant>) => {
    const plantSunDropCount = plantList.reduce((pre, cur) => pre + (cur.sunDropCount ? cur.sunDropCount : 0), 0) // 植物阳光掉落数量
    const sunDropCount = defaultUserInfo().sunDropCount // 默认阳光掉落数量
    userInfo.sunDropCount = plantSunDropCount + sunDropCount // 阳光掉落总数量
    return userInfo
}


export {
    recordError,
    render,
    getSunLimitTime,
    formatTimeSecondToHMS,
    recalculateSunInfo,
}